<template>
  <el-card shadow="hover">
    <template #header>
      <el-button
        type="primary"
        :icon="Plus"
        @click="showUpdateTrademarkDialog()"
        >添加</el-button
      >
    </template>
    <el-table border :data="trademark" class="trademark" v-loading="loading">
      <el-table-column label="序号" width="80" align="center" type="index">
      </el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌Login" prop="logoUrl">
        <template v-slot="{ row }">
          <el-image :src="row.logoUrl" lazy class="trademarkimg" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            :icon="Edit"
            type="warning"
            size="small"
            @click="showUpdateTrademarkDialog(row)"></el-button>

          <el-button
            :icon="Delete"
            type="danger"
            size="small"
            @click="deleteTrademarkFormData(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      layout="  prev, pager, next, jumper,->,sizes,total,"
      :total="total"
      @size-change="getTrademarkApi"
      @current-change="getTrademarkApi" />

    <el-dialog
      v-model="dialogVisible"
      :title="`${trademarkFormData.id > 0 ? '修改' : '添加'}品牌`">
      <template #footer>
        <el-form
          :model="trademarkFormData"
          :rules="trademarkFormRules"
          ref="trademarkFormRef">
          <el-form-item label="品牌名称" label-width="120px" prop="tmName">
            <el-input
              placeholder="请输入品牌名"
              v-model="trademarkFormData.tmName" />
          </el-form-item>
          <el-form-item label="品牌LOGO" label-width="120px" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :action="`${BASE_URL}/admin/product/upload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <template #tip>
                <p>只能上传jpg/png文件，且不超过50kb</p>
              </template>
              <img
                v-if="trademarkFormData.logoUrl"
                :src="trademarkFormData.logoUrl"
                class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addTardemark"> 确定 </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import type {
  TrackdemarkList,
  TrackdemarkItem,
} from "@/api/types/trademark.ts";
import {
  trademarkDataApi,
  trademarkAddApi,
  trademarkUpdateApi,
  trademarkDeleteApi,
} from "@/api/trademark.ts";
import type { UploadProps } from "element-plus";

defineOptions({
  name: "trademark",
});

//定义列表初始参数
const trademark = ref<TrackdemarkList>([]);
const total = ref(100);
const loading = ref(false);
//当前页数
const currentPage = ref(1);
//一页显示多少条
const pageSize = ref(3);
//控制弹框的显示与隐藏
const dialogVisible = ref(false);
//封装发送获取品牌管理列表数据函数
const getTrademarkApi = async () => {
  loading.value = true;
  const res = await trademarkDataApi(currentPage.value, pageSize.value);
  trademark.value = res.records;
  total.value = res.total;
  pageSize.value = res.size;
  loading.value = false;
};
//发送请求获取数据
onMounted(getTrademarkApi);

//品牌添加
const BASE_URL = import.meta.env.VITE_API_URL;
//新增品牌
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkFormData.logoUrl = response.data;
};

//判断图片格式或图片大小
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const valldFileTypes = ["image/jpeg", "image/jpg", "image/png"];
  if (!valldFileTypes.includes(rawFile.type)) {
    ElMessage.error("上传图片类型错误!");
    return false;
  } else if (rawFile.size > 200 * 1024) {
    ElMessage.error("图片不能大于200kB!");
    return false;
  }
  return true;
};
//定义数据
const trademarkFormData = reactive({
  id: -1,
  tmName: "",
  logoUrl: "",
});
//表单验证
const trademarkFormRules = reactive({
  tmName: [
    {
      required: true,
      message: "请输入品牌名",
      trigger: "blur",
    },
    { min: 2, max: 10, message: "长度必须在2-10个之间", trigger: "blur" },
  ],
  logoUrl: {
    required: true,
    message: "请上传品牌Logo",
  },
});
//获取组件实例对象
const trademarkFormRef = ref();
//点击确定进行验证
const addTardemark = async () => {
  await trademarkFormRef.value.validate();
  const id = trademarkFormData.id;
  //放送添加表单列表请求
  if (id > 0) {
    await trademarkUpdateApi(trademarkFormData);
  } else {
    await trademarkAddApi(trademarkFormData.logoUrl, trademarkFormData.tmName);
  }
  ElMessage.success(`${id > 0 ? "修改" : "添加"}  品牌成功`);

  //获取表单数据
  getTrademarkApi();
  // //重置数据
  // trademarkFormData.logoUrl = "";
  // trademarkFormData.tmName = "";
  dialogVisible.value = false;
};

//修改品牌数据
const showUpdateTrademarkDialog = (
  row: TrackdemarkItem = { logoUrl: "", tmName: "", id: -1 }
) => {
  dialogVisible.value = true;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.id = row.id;
  trademarkFormRef.value?.clearValidate();
};

//删除
const deleteTrademarkFormData = async (row: TrackdemarkItem) => {
  ElMessageBox.confirm(`你确定删除${row.tmName}吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      trademarkDeleteApi(row.id);
      getTrademarkApi();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
</script>

<style scoped lang="scss">
.trademark {
  margin: 20px 0px;
}
.trademarkimg {
  width: 150px;
  height: 80px;
}
.avatar-uploader {
  :deep(.avatar) {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
}

.avatar-uploader {
  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
